package com.cdream.basic.mq.kafka;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Properties;

import static com.cdream.basic.mq.kafka.KafkaConst.BROKER_LIST;
import static com.cdream.basic.mq.kafka.KafkaConst.TOPIC;

/**
 * @author cdream
 * @date 2022/8/7
 */
@Slf4j
public class KafkaConsumerDemo2 {
    private static final String GROUP_ID = "group.mygroup";

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("key.deserializer", StringDeserializer.class.getName());
        props.put("value.deserializer", StringDeserializer.class.getName());
        props.put("bootstrap.servers", BROKER_LIST);
        props.put("group.id", GROUP_ID);
        // 关闭自动提交
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,false);
        KafkaConsumer<String, String> consumer= new KafkaConsumer<>(props);
        log.info("分区信息：{}",consumer.partitionsFor("mytopic"));
        consumer.subscribe(CollUtil.newArrayList(TOPIC));
        while (true){
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.value());
                // doJiaQian
            }
            // 挂了
            consumer.commitSync();

        }
    }
}
